package com.kadron.paging;

public class PagingService {

	private KRowService kRowService;
	
	private PagingService() {
		super();
	}
	
	public PagingService(KRowService kRowService) {
		this();
		this.kRowService = kRowService;
	}
	
	public void show(KRowParent parent, Integer page) {
		if (parent == null || page == null || page <= 0 || page > parent.getModelContainer().getLast()) {
			return;
		}
		try {			
			parent.getModelContainer().setCurrentPage(page);
			int records = parent.getModelContainer().getRecords();
			int firstResult = --page*records;
			kRowService.getModels(parent, firstResult, records);
			if (parent.getModelContainer().getCount() == null) {
				Long count = kRowService.getCount(parent);
				parent.getModelContainer().setCount(count);
			}
			parent.getModelContainer().initPages();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void previousNext(KRowParent parent,Boolean next) {
		if (parent == null) {
			return;
		}
		int currentPage = parent.getModelContainer().getCurrentPage();
		if (next) {
			show(parent,currentPage+1);			
		} else {
			show(parent,currentPage-1);						
		}
	}
	
	public void fast(KRowParent parent,Boolean next) {
		if (parent == null) {
			return;
		}
		int currentPage = parent.getModelContainer().getCurrentPage();
		int fastStep = parent.getModelContainer().getFastStep();
		if (next) {
			show(parent,currentPage+fastStep);			
		} else {
			show(parent,currentPage-fastStep);						
		}
	}
	
	public void setRows(KRowParent parent, Integer records) {
		parent.getModelContainer().setRecords(records);
		int last = parent.getModelContainer().getLast();
		int currentPage = parent.getModelContainer().getCurrentPage();
		if (currentPage > last) {
			show(parent, last);
		} else {
			show(parent, currentPage);			
		}
	}
	
	public void setMax(KRowParent parent) {
		parent.getModelContainer().setRecords(Integer.MAX_VALUE);
		parent.getModelContainer().setCurrentPage(ModelContainer.DEFAULT_PAGE);
		kRowService.getAllModels(parent);
	}
	
}